import type {AxiosInstance, AxiosRequestConfig} from "axios";
import axios from "axios";

export class Request{
    instance: AxiosInstance
    constructor(config: AxiosRequestConfig, globalInterceptor: boolean = false) {
        this.instance = axios.create(config)
        if (globalInterceptor){
            Request.addReqInterceptor(this.instance)
            Request.addResInterceptor(this.instance)
        }
    }

    request(config: AxiosRequestConfig) {
        return this.instance.request(config)
    }

    static addReqInterceptor(instance: AxiosInstance) {
        instance.interceptors.request.use(config => {
            // 请求拦截的逻辑处理
            return config
        }, err => {
            return Promise.reject(err)
        })
    }

    static addResInterceptor(instance: AxiosInstance) {
        instance.interceptors.response.use(res => {
            // 响应拦截的逻辑处理
            return res
        }, err => {
            return Promise.reject(err)
        })
    }
}


const request = new Request({
    baseURL: 'http://localhost:8080',
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json'
    }
})

request.request({
    url: '/api/user',
    method: 'get',
    params: {
        name: 'zhangsan'
    }
}).then(res => {
    console.log(res)
}).catch(err => {
    console.log(err)
})
